﻿using KTD.Web.Models;
using KTD.Web.Models.VD;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XXS.Common.BaseDataAccessLayer;
using XXS.Common.Paginate;

namespace KTD.Web.BLL
{
    public class NewsManager
    {
        private readonly IBaseDAL<News> _NewsDal;
        public NewsManager()
        {
            _NewsDal = new BaseDAL<News>(new DB());
        }

        /// <summary>
        /// 获取新闻列表
        /// </summary>
        /// <param name="im"></param>
        /// <returns></returns>
        public virtual IPaginate<NewsVD> GetListBy(NewsQD im)
        {
            var res = _NewsDal.FindList();
            if (!string.IsNullOrEmpty(im.Query))
            {
                res = res.Where(n => n.title.Contains(im.Query) || n.content.Contains(im.Query));
            }
            if (im.cityId != null)
            {
                res = res.Where(n => n.cityId == im.cityId);
            }
            if (im.pid!=0)
            {
                res = res.Where(n =>n.pid==im.pid);
            }
            var list = res.OrderByDescending(n => n.CreateDateTime)
                .ToPaginate(im,n => new NewsVD().MapFrom(n));
            return list;
        }


        public void Create(NewsCUD im)
        {
            News modeloLD = _NewsDal.Find(im.Id);
            
            if (modeloLD != null)
            {
                return;
            }
            News model = new News();
            im.MapTo(model);
            if (model.pid == 1) { model.des = "楼盘头条"; }
            else if (model.pid == 2) { model.des = "吃瓜吐槽"; }
            else if (model.pid == 3) { model.des = "销售技巧"; }
            else { model.des = "政策解读"; }
            _NewsDal.Create(model);
        }

        public void Update(NewsCUD im)
        {
            News model = _NewsDal.Find(im.Id);
            var thumb = model.thumb;
            if (model == null)
            {
                throw new Exception("错误的ID");
            }
            im.MapTo(model);
            if (model.pid == 1) { model.des = "楼盘头条"; }
            else if (model.pid == 2) { model.des = "吃瓜吐槽"; }
            else if (model.pid == 3) { model.des = "销售技巧"; }
            else { model.des = "政策解读"; }
            if (string.IsNullOrEmpty(im.thumb)) {
                model.thumb = thumb;
            }
            _NewsDal.Update(model);
        }

        public NewsCUD Find(int id)
        {
            News model = _NewsDal.Find(id);
            model.hits = model.hits + 1;
            _NewsDal.Update(model);
            return new NewsCUD().MapFrom(model);
        }

        public void Delete(int id)
        {
            News model = _NewsDal.Find(id);
            if (model == null)
            {
                throw new Exception("错误的ID");
            }
            _NewsDal.Delete(model);
        }
    }
}